var {getLoginedUser, fnLoading, fnHideLoading, fnSuccess, fnFail} = require('../../utils/index');
import _ from '../../utils/underscore.js';
import {get, lsGetStr,post} from '../../utils/request.js';
import {floatTool,payOrder} from '../../utils/util.js'
import { checkLoginAsyc } from "../../utils/util.js";
const app = getApp()
Page({
  navTo() {
   
  },
    /**
     * 页面的初始数据
     */
    data: {
        softOther:false,
        other: [],
        num: 1,
        useTotal:0,//默认不使用佣金
        numOther:1
    },
    adds:function(){
      var numOther = this.data.numOther;
      numOther++;
      this.data.numOther = numOther;
      this.setData({
        numOther: numOther
      })
      this.calculateTotal();

    },
  checkboxChange(e){
    //if( e.detail.value)
    this.setData({
      checked: !!e.detail.value.length
    })
    this.calculateTotal();
    //console.log('checkbox发生change事件，携带value值为：', e.detail.value)
  },
    cuts:function(){
      
      var numOther = this.data.numOther;
      if (numOther <= 1) {
        if (numOther==1){
          return fnFail('代码文档和源码最少要选择一个');
        }
        return
      } else {
        numOther--;
        this.data.numOther = numOther;
      }
      this.setData({
        numOther: numOther
      })
      this.calculateTotal();
    },
    add: function (e) {
      // 商品服务
        let other = this.data.other;
        let index = e.currentTarget.dataset.index;
        var id = e.target.dataset.id;
        var num = other[index].numberSelected;
        console.log(num);
       
        num++;
        var obj = {};
        obj['num' + index] = (num);
        
      other = [...other.slice(0, index), Object.assign({}, other[index], {numberSelected: (num)}), ...other.slice(index + 1)];
      console.log(other)
        this.setData({
            other: other,
        });
      post({
        path: "/order/updateCartShopNum",
        data: {
          skey: lsGetStr('skey'),
          id: this.data.other[index].cartId,
          number: num,
        }
      }).then(function (res) {
        
        // fnSuccess("修改成功")
      })
      this.calculateTotal();

    },
 
    cut: function (v) {
      
      // 商品服务
      let that=this;
        let other = this.data.other;
        let index = v.currentTarget.dataset.index;
        var num = other[index].numberSelected;
       
        if (num > 0) {
          num--;
        }
        
      post({
        path: "/order/updateCartShopNum",
        data: {
          skey: lsGetStr('skey'),
          id: that.data.other[index].cartId,
          number: num
        }
      }).then(function (res) {
      })

        if(num<1){
        post({
          path: "/order/removeShoppingcart",
          data: {
            skey: lsGetStr('skey'),
            id: that.data.other[index].cartId
          }
        }).then(function(res){
          that.onLoad(that.options);
        })
             
      }
      var obj = {};
      obj['num' + index] = (num);
      
      other = [...other.slice(0, index), Object.assign({}, other[index], { numberSelected: (num) }), ...other.slice(index + 1)];
      this.setData({
        other: other,
      });
      this.calculateTotal();
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this;
      wx.showShareMenu();//
      wx.hideTabBar();
      app.customTabBar()
        fnLoading('加载中...');
      if (!that.data.user){
        get({
          path: "user/getInfo"
        })
          .then(function (res) {
              that.setData({
                user:res.user
              })
          })
      }
        get({
          path: "/order/shoppingcartItems" ,
        }).then(function (res) {
          fnHideLoading();//隐藏
          let list = res.map(function (item) {
            item.numberSelected = parseInt(item.numberSelected);
            return item;
          });
          let softShop = _.find(list,(item)=>{
            return item.type1=='2';
          })
          that.setData(Object.assign({}, {
            other: list,
            softOther: softShop || false,
            options: options,
          }, softShop ? {} : { numOther: 1,checked:false}));
            wx.stopPullDownRefresh();
          that.calculateTotal();
        })
    },
    onPullDownRefresh() {
        this.onLoad(this.data.options || {});
    },
  calculateTotal() {
        let that = this, list = this.data.other;
        list = list.map(function (item) {
            return floatTool.multiply(item.price, item.numberSelected);
        });
     
      let total = floatTool.subtract(
        _.reduce(list, function (a, b) {
          return floatTool.add(a, b)
        }, 0),
        that.data.useTotal
      );
      if(this.data.checked){
        total = floatTool.add(total, floatTool.multiply(this.data.numOther,300));
      }
        this.setData({
          total: total
        })
    },
  inputNum(e){ //输入佣金
    let key = e.currentTarget.dataset.name,
      current = parseInt(e.detail.value),
      total = parseInt(this.data.user.pointsNow);
      if (current > total){
        current = total;
      }
      this.setData({
        [key]: current
      })
  },
    //支付
    pay: function (e) {
        let that = this;
        let other = this.data.other;
      
      get({
        path: "user/getInfo"
      }).then(function(res){
        // console.log(res)
        if (!res.user.phone){
          that.setData({
            verifyPhone: true,
          })
        }else{
          that.pay1();
        }
      })

      // getLoginedUser()
      //   .then(user => {
      //     console.log("user=>",user);
      //     if (!user.phone) {
      //       that.setData({
      //         verifyPhone: true,
      //       })
      //     } else {
      //       that.pay1();
      //     }
      //   })
      
    },
  pay1(){
      fnLoading('提交中...');
      let that = this;
      let other = this.data.other;

      let order = {
        skey: lsGetStr('skey'),
        type: 1,
        total: that.data.useTotal,
        shopIds: other.map(function (item) {
          return item.id
        }).join(','),
        numbers: other.map(function (item) {
          return parseInt(item.numberSelected)
        }).join(','),
        payTotal: floatTool.add(that.data.total, that.data.useTotal),
        softDocNum: that.data.checked ? that.data.numOther : 0
      };
      post({
        path: "/order/create",
        data: order
      })
        .then(function (res) {
          console.log(res);
          fnHideLoading();
          var outTradeNo = res.no;
          var payTotal = order.payTotal;
          var body = res.remark || '闻权企服-服务订单支付';
          return payOrder({
            outTradeNo, body, payTotal
          })
            .then(function (payRes) {
              fnSuccess('支付成功，即将跳转')
              setTimeout(function () {
                wx.navigateTo({
                  url: '../order-from/index',
                })
              }, 2000)
            })
            .catch(function (payError) {
              fnFail('支付失败，请稍后再试');
              setTimeout(function () {
                wx.navigateTo({
                  url: '../order-from/index',
                })
              }, 2000)
            })
        })
        .catch(function (res) {
          console.log(res);
          fnHideLoading()
        })
    },
   

  onShow() {
    this.onLoad(this.data.options || {});
  },
   
});